
package com.daykw.vip.api.service;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.bson.Document;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daykw.vip.api.model.Page;
import com.daykw.vip.api.model.Result;
import com.daykw.vip.api.model.TArticleInfo;
import com.daykw.vip.api.model.TArticleTask;
import com.daykw.vip.api.model.TAuthorTask;
import com.daykw.vip.api.model.TNewUid;
import com.daykw.vip.api.model.UpdateAid;
import com.daykw.vip.api.util.Const;
import com.daykw.vip.api.util.MongoDBUtil;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;

@Component
public class VipApiService {

	private static Logger logger = Logger.getLogger(VipApiService.class);

	@Resource
	private NutDao dao;

	public Page getArticleByUid(String user_id, Integer pageNum, Integer pageSize) {
		try {
			Pager pager = dao.createPager(pageNum, pageSize);
			Criteria cri = Cnd.cri();
			cri.where().andEquals("user_id", user_id);
			List<TArticleInfo> list = dao.query(TArticleInfo.class, cri, pager);
			JSONArray array = new JSONArray();
			MongoCollection<org.bson.Document> article_coll = MongoDBUtil.instance.getCollection(Const.MDB_DB,
					"article");

			for (TArticleInfo info : list) {
				JSONObject ijson = new JSONObject();
				org.bson.Document doc = MongoDBUtil.instance.findByOne(article_coll, "aid", info.getArticle_id());
				if (doc != null && !doc.isEmpty()) {
					ijson = JSONObject.parseObject(doc.toJson());
				}

				array.add(ijson);
			}

			int count = dao.count(TArticleInfo.class, cri);
			Page p = new Page(count, pager.getPageNumber(), pager.getPageSize());
			p.setCode(Const.SUC);
			p.setData(array);
			return p;
		} catch (Exception e) {
			Page p = new Page();
			p.setCode(Const.FAIL_500);
			p.setData(new JSONArray());
			p.setMsg("内部错误，请求异常");
			logger.error("", e);
			return p;
		}

	}

	public Result getArticleByAid(String aid) {
		Result ret = new Result();
		try {

			JSONArray array = new JSONArray();
			MongoCollection<org.bson.Document> article_coll = MongoDBUtil.instance.getCollection(Const.MDB_DB,
					"article");

			JSONObject ijson = new JSONObject();
			org.bson.Document doc = MongoDBUtil.instance.findByOne(article_coll, "aid", aid);
			if (doc != null && !doc.isEmpty()) {
				ijson = JSONObject.parseObject(doc.toJson());
			}

			array.add(ijson);

			ret.setCode(Const.SUC);
			ret.setData(array);
			return ret;
		} catch (Exception e) {

			ret.setCode(Const.FAIL_500);
			ret.setData(new JSONArray());
			ret.setMsg("内部错误，请求异常");
			logger.error("", e);
			return ret;
		}

	}

	public Result getCommentsByAid(String aid) {
		Result ret = new Result();
		try {

			MongoCollection<org.bson.Document> comment_coll = MongoDBUtil.instance.getCollection(Const.MDB_DB,
					"comment");

			JSONArray cms = new JSONArray();

			MongoCursor<Document> comms = MongoDBUtil.instance.find(comment_coll, Filters.eq("aid", aid));

			while (comms.hasNext()) {
				Document _doc = comms.next();
				JSONObject cjson = new JSONObject();
				if (_doc != null && !_doc.isEmpty()) {
					cjson = JSONObject.parseObject(_doc.toJson());
				}
				cms.add(cjson);
			}

			ret.setCode(Const.SUC);
			ret.setData(cms);
			return ret;
		} catch (Exception e) {

			ret.setCode(Const.FAIL_500);
			ret.setData(new JSONArray());
			ret.setMsg("内部错误，请求异常");
			logger.error("", e);
			return ret;
		}

	}

	public Result getArticleByAids(String[] aids) {
		Result ret = new Result();
		try {

			JSONArray array = new JSONArray();
			MongoCollection<org.bson.Document> article_coll = MongoDBUtil.instance.getCollection(Const.MDB_DB,
					"article");
//			MongoCollection<org.bson.Document> comment_coll = MongoDBUtil.instance.getCollection(Const.MDB_DB,
//					"comment");

			MongoCursor<org.bson.Document> docs = MongoDBUtil.instance.find(article_coll, Filters.in("aid", aids));

			while (docs.hasNext()) {
				Document adoc = docs.next();
				JSONObject ijson = JSONObject.parseObject(adoc.toJson());
//				if (adoc != null && !adoc.isEmpty()) {
//					ijson = JSONObject.parseObject(adoc.toJson());
//					String aid = adoc.getString("aid");
//					JSONArray cms = new JSONArray();
//					MongoCursor<Document> comms = MongoDBUtil.instance.find(comment_coll, Filters.eq("aid", aid));
//
//					while (comms.hasNext()) {
//						Document _doc = comms.next();
//						JSONObject cjson = new JSONObject();
//						if (_doc != null && !_doc.isEmpty()) {
//							cjson = JSONObject.parseObject(_doc.toJson());
//						}
//						cms.add(cjson);
//					}
//					ijson.put("comment_list", cms);
//				}
				array.add(ijson);
			}

			ret.setCode(Const.SUC);
			ret.setData(array);
			return ret;
		} catch (Exception e) {

			ret.setCode(Const.FAIL_500);
			ret.setData(new JSONArray());
			ret.setMsg("内部错误，请求异常");
			logger.error("", e);
			return ret;
		}

	}

	/**
	 * 根据抓取时间获取文章
	 * 
	 * @param date
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public Page getArticleByCreateDate(Integer max_date, Integer pageNum, Integer pageSize) {
		Integer min_date = null;
		DateFormat format = new SimpleDateFormat("yyyyMMddHH");
		try {
			Date md = format.parse(max_date + "");
			Calendar c = Calendar.getInstance();
			c.setTime(md);
			c.add(Calendar.HOUR, -1);
			min_date = Integer.valueOf(format.format(c.getTime()));
		} catch (Exception e) {
		}
		Sql sql = Sqls.create("select article_id from t_article_info $condition");
		Cnd cnd = Cnd.where("create_date", "=", min_date);
		int count = dao.count("t_article_info", cnd);
		Pager pager = new Pager(pageNum, pageSize);
		Page p = new Page(count, pageNum, pageSize);
		sql.setCallback(Sqls.callback.strList());
		sql.setPager(pager);
		sql.setCondition(cnd);
		dao.execute(sql);
		List<String> list = sql.getList(String.class);
		p.setCode(Const.SUC);
		p.setData(list);
		return p;
	}

	/**
	 * 根据文章日期
	 * 
	 * @param date
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public Page getArticleByPuhDate(Integer date, Integer pageNum, Integer pageSize) {
		Sql sql = Sqls.create("select article_id from t_article_info $condition");
		Cnd cnd = Cnd.where("pdate", "=", date);
		int count = dao.count("t_article_info", cnd);
		Pager pager = new Pager(pageNum, pageSize);
		Page p = new Page(count, pageNum, pageSize);
		sql.setCallback(Sqls.callback.strList());
		sql.setPager(pager);
		sql.setCondition(cnd);
		dao.execute(sql);
		List<String> list = sql.getList(String.class);
		p.setCode(Const.SUC);
		p.setData(list);
		return p;
	}

	/**
	 * 获取用户详情
	 * 
	 * @param userid
	 * @return
	 */
	public Result getAuthorbyUserid(String userid) {
		Result ret = new Result();
		Sql sql = Sqls.create("select json,update_time,create_time from t_author_task $condition");
		sql.setCallback(Sqls.callback.record());
		sql.setCondition(Cnd.where("user_id", "=", userid));
		dao.execute(sql);
		Record record = sql.getObject(Record.class);
		if (record == null) {
			ret.setCode(Const.FAIL_400);
			ret.setData(new JSONObject());
			ret.setMsg("用户[" + userid + "]不存在");
			return ret;
		}
		if (record.getTimestamp("update_time") == null) {
			record.set("update_time", record.getTimestamp("create_time"));
		}
		Timestamp ct = record.getTimestamp("create_time");
		Timestamp ut = record.getTimestamp("update_time");
		DateFormat DF = new SimpleDateFormat("yyyyMMddHHmmss");
		record.set("create_time", DF.format(ct));
		record.set("update_time", DF.format(ut));
		ret.setCode(Const.SUC);
		ret.setData(record);
		return ret;
	}

	/**
	 * 获取用户详情
	 * 
	 * @param userid
	 * @return
	 */
	public Result getAuthorbyUserids(String[] userid) {
		Result ret = new Result();
		Sql sql = Sqls.create("select json,status from t_author_task $condition");
		sql.setCallback(Sqls.callback.records());
		sql.setCondition(Cnd.where("user_id", "in", userid));
		dao.execute(sql);
		List<Record> list = sql.getList(Record.class);
		if (CollectionUtils.isEmpty(list)) {
			ret.setCode(Const.FAIL_400);
			ret.setData(new JSONObject());
			ret.setMsg("用户[" + userid + "]不存在");
			return ret;
		}
		ret.setCode(Const.SUC);
		ret.setData(list);
		return ret;
	}

	/**
	 * 添加用户uid
	 * 
	 * @param userid
	 * @return
	 */
	public Result addUids(String[] uids) {
		Result ret = new Result();
		StringBuffer buf = new StringBuffer();
		for (String uid : uids) {
			TNewUid u = dao.fetch(TNewUid.class, Cnd.where("uid", "=", uid));
			if (u == null) {
				u = new TNewUid();
				u.setUid(uid);
				u.setCreate_date(new Date());
				u.setCreate_time(new Date());
				u.setStatus(0);
				dao.fastInsert(u);

				TAuthorTask author = dao.fetch(TAuthorTask.class, Cnd.where("user_id", "=", uid));

				if (author == null) {
					author = new TAuthorTask();
					author.setUser_id(uid);
					author.setUrl("http://www.xiaohongshu.com/user/profile/" + uid);
					author.setCreate_time(new Date());
					author.setStatus(0);
					dao.fastInsert(author);
				} else {
					dao.update(TAuthorTask.class, Chain.make("status", 0).add("update_time", new Date()),
							Cnd.where("user_id", "=", uid));
				}
			} else {
				TAuthorTask author = dao.fetch(TAuthorTask.class, Cnd.where("user_id", "=", uid));
				if (author == null) {
					author = new TAuthorTask();
					author.setUser_id(uid);
					author.setUrl("http://www.xiaohongshu.com/user/profile/" + uid);
					author.setCreate_time(new Date());
					author.setStatus(0);
					dao.fastInsert(author);
				} else {
					dao.update(TAuthorTask.class, Chain.make("status", 0).add("update_time", new Date()),
							Cnd.where("user_id", "=", uid));
				}
			}
		}
		ret = this.getAuthorbyUserids(uids);
		ret.setCode(Const.SUC);
		return ret;
	}

	public boolean getRestMaxDate() {
		Calendar nowTime = Calendar.getInstance();
		nowTime.add(Calendar.MINUTE, -10);// 30分钟后的时间
		Date now = nowTime.getTime();

		Date cdate = (Date) dao.func2(UpdateAid.class, "max", "create_time", null);
		Date udate = (Date) dao.func2(UpdateAid.class, "max", "update_time", null);
		Date curDate = null;
		if (udate != null) {
			if (cdate.after(udate)) {
				curDate = cdate;
			} else {
				curDate = udate;
			}
		} else {
			curDate = cdate;
		}
		long between = (now.getTime() - curDate.getTime()) / 1000;// 除以1000是为了转换成秒
		long min = between / 60;
		min = Math.abs(min);
		if (min <= 10) {
			return false;
		} else {
			return true;
		}

	}

	public Result restAids(String[] aids) {
		Result ret = new Result();
		try {

			for (int i = 0; i < aids.length; i++) {
				String aid = aids[i];
			
//				TAuthorTask author = dao.fetch(TAuthorTask.class, Cnd.where("user_id", "=", userid));
//
//				if (author == null) {
//					author = new TAuthorTask();
//					author.setUser_id(userid);
//					author.setUrl("http://www.xiaohongshu.com/user/profile/" + userid);
//					author.setCreate_time(new Date());
//					author.setStatus(0);
//					dao.fastInsert(author);
//				} else {
//					dao.update(TAuthorTask.class, Chain.make("status", 0).add("update_time", new Date()),
//							Cnd.where("user_id", "=", userid));
//				}
//
//				String aid = url.substring(url.lastIndexOf("/") + 1, url.length());
//				TArticleTask article = dao.fetch(TArticleTask.class, Cnd.where("aid", "=", aid));
//
//				if (article == null) {
//					article = new TArticleTask();
//					article.setAid(aid);
//					article.setUrl(url);
//					article.setStatus(0);
//					article.setComment_status(0);
//					article.setCreate_time(new Date());
//					article.setUser_id(userid);
//					dao.fastInsert(article);
//				} else {
//					dao.update(TArticleTask.class,
//							Chain.make("status", 0).add("comment_status", 0).add("last_aid", null),
//							Cnd.where("aid", "=", aid));
//				}

				UpdateAid ua = dao.fetch(UpdateAid.class, Cnd.where("aid", "=", aid));
				//
				if (ua == null) {
					ua = new UpdateAid();
					ua.setAid(aid);
					ua.setUrl("http://www.xiaohongshu.com/discovery/item/"+aid);
					ua.setCreate_time(new Date());
					
					ua.setStatus(0);
					ua.setComment_status(0);
					dao.fastInsert(ua);
				} else {
					dao.update(UpdateAid.class, Chain.make("status", 0).add("comment_status", 0).add("last_aid", null)
							.add("update_time", new Date()), Cnd.where("aid", "=", aid));
				}
			}

			ret.setCode(Const.SUC);
			ret.setMsg("操作成功");
			return ret;
		} catch (Exception e) {

			ret.setCode(Const.FAIL_500);
			ret.setData(new JSONArray());
			ret.setMsg("内部错误，请求异常");
			logger.error("", e);
			return ret;
		}

	}

	public Result getRestList(String[] aids, String[] urls, String astatus, String cstatus) {
		Result ret = new Result();
		try {
			List<UpdateAid> list = new ArrayList<UpdateAid>();
			if ((aids == null || aids.length == 0) && (urls == null || urls.length == 0)) {
				ret.setCode(Const.FAIL);
				ret.setMsg("aids 或者 urls 没有赋值");
				return ret;
			}
			if (aids != null && aids.length > 0 && urls != null && urls.length > 0) {
				ret.setCode(Const.FAIL);
				ret.setMsg("aids 和 urls 不能同时赋值");
				return ret;
			}
			Criteria cri = Cnd.cri();

			if (urls != null && urls.length > 0) {
				cri.where().andIn("url", urls);
				if (StringUtils.isNotEmpty(astatus)) {
					cri.where().andEquals("status", astatus);
				}
				if (StringUtils.isNotEmpty(cstatus)) {
					cri.where().andEquals("comment_status", cstatus);
				}
				list = dao.query(UpdateAid.class, cri);
			} else {
				cri.where().andIn("aid", aids);
				if (StringUtils.isNotEmpty(astatus)) {
					cri.where().andEquals("status", astatus);
				}
				if (StringUtils.isNotEmpty(cstatus)) {
					cri.where().andEquals("comment_status", cstatus);
				}
				list = dao.query(UpdateAid.class, cri);
			}

			ret.setCode(Const.SUC);
			ret.setData(list);
			return ret;
		} catch (Exception e) {

			ret.setCode(Const.FAIL_500);
			ret.setData(new JSONArray());
			ret.setMsg("内部错误，请求异常");
			logger.error("", e);
			return ret;
		}

	}
}
